<?php

namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\model\Factory as FactoryModel;
use think\Db;
use app\common\service\Factory;

/**
 * 订单加一级，工厂的管理
 * @author zhuguosen 905502314@qq.com
 * @date 2022/6/1
 * @package app\mp\admin
 */
class FactoryV2 extends Admin
{
    protected $hisiModel = 'Factory';//模型名称[通用添加、修改专用]
    protected $hisiValidate = 'Factory';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名
    /**
     * @var \app\common\service\Factory
     */
    protected $factoryServer;
    protected $menu_factory;
    protected $list;
    protected $list_tree;

    public function initialize()
    {
        parent::initialize();
        $this->factoryServer = new Factory();
        list($this->list, $this->list_tree) = $this->factoryServer->getAllTree([]);
        $this->assign('menu_factory', $this->list_tree);
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $where = $data = [];
            $whereRaw = '1=1';
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $keyword = $this->request->param('keyword/s');
            $pids = trim($this->request->param('pids/s', ''));
            if ($pids != '') {
                $whereRaw .= " and pid in ($pids) OR id in ($pids)";
            } else {
                $where[] = ['pid', '=', 0];
            }
            $where[] = ['status', 'eq', 1];
            if ($keyword) {
                $where[] = ['name', 'like', "%{$keyword}%"];
            }
            $data['data'] = db('factory')->where($where)->whereRaw($whereRaw)->page($page)->limit($limit)->order('order desc, id desc')->select();
            $data['data'] = $this->_dealwith_index($data['data']);
            $data['count'] = db('factory')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        return $this->fetch();
    }

    private function _dealwith_index($data)
    {
        $ids = [];
        foreach ($data as $k => $v) {
            $data[$k]['type'] = $v['type'] == 0 ? '自家' : '外发';
            $ids[] = $v['id'];
            //父工厂信息
            $this->factoryServer->temp = [];
            $parentList = $this->factoryServer->getParentStr_all_info($v['id']);
            $this->factoryServer->temp = array_reverse($this->factoryServer->temp);
            $data[$k]['parent_list'] = $this->factoryServer->temp;
            unset($data[$k]['parent_list'][count($data[$k]['parent_list']) - 1]);
            $data[$k]['name_pids'] = "";
            foreach ($data[$k]['parent_list'] as $k2 => $v2) {
                $data[$k]['name_pids'] .= "{$v2['name']}>";
            }
            //子工厂集
            $data[$k]['childList'] = $this->factoryServer->getChildTree($v['id'], 'children');
            //2,树转一维数组
            $data[$k]['childList_array'] = $this->_childList_array_list_tree($data[$k]['childList']);
        }
        return $data;
    }

    private function _childList_array_list_tree($list_tree)
    {
        $res_list = [];
        foreach ($list_tree as $k => $v) {
            $res_list[] = $v;
            if (isset($v['children'])) {
                foreach ($v['children'] as $k2 => $v2) {
                    $v2['name'] = "└─{$v2['name']}";
                    $res_list[] = $v2;
                    if (isset($v2['children'])) {
                        foreach ($v2['children'] as $k3 => $v3) {
                            $v3['name'] = "&nbsp;&nbsp;└─{$v3['name']}";
                            $res_list[] = $v3;
                            if (isset($v3['children'])) {
                                foreach ($v3['children'] as $k4 => $v4) {
                                    $v4['name'] = "&nbsp;&nbsp;&nbsp;&nbsp;└─{$v4['name']}";
                                    $res_list[] = $v4;
                                }
                            }
                        }
                    }
                }
            }
        }
        return $res_list;
    }

    /**
     * [通用方法]添加页面展示和保存
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->post();
            $param['pid'] = intval($param['pid']);
            $param['type_level'] = $param['type_level'] ?? 0;
            $param['type'] = $this->get_type($param);
            //检测的这个工厂是否先上一极工厂，不能越极作为父工厂
            $temp = $this->_check_get_level($param);
            if ($temp['code'] > 0) {
                return $this->error($temp['msg']);
            }
            db('factory')->insert([
                'pid' => $param['pid'],
                'level' => $param['level'],
                'type' => $param['type'],
                'name' => $param['name'],
                'update_time' => time(),
                'create_time' => time(),
            ]);
            return $this->success('保存成功', '');
        }
        $type_level = $this->request->param('type_level/d', 0);
        $typeMap = ['0' => '自家', '1' => '外发'];
        $this->assign('typeMap', $typeMap);
        $this->assign('type_level', $type_level);
        return $this->fetch('form');
    }

    /**
     * 检查父工厂等级选择
     * 1，当前等级与父等级对比不可知
     * @param $param
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/1
     */
    private function _check_get_level(&$param)
    {
        $p_level = 0;
        if ($param['pid'] > 0) {
            $info = db('factory')->where('id', $param['pid'])->find();
            $p_level = $info['level'];
        }
        if (($p_level + 1) != $param['type_level']) {
            return ['code' => 2, 'msg' => '父工厂等级选择不对',];
        }
        $param['level'] = $p_level + 1;
        return ['code' => 0, 'msg' => '',];
    }

    /**
     * [通用方法]编辑页面展示和保存
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function edit()
    {
        if ($this->request->isPost()) {// 数据验证
            $param = $this->request->post();
            $param['pid'] = intval($param['pid']);
            $param['type_level'] = $param['type_level'] ?? 0;
            $param['type'] = $this->get_type($param);
            //检测的这个工厂是否先上一极工厂，不能越极作为父工厂
            $temp = $this->_check_get_level($param);
            if ($temp['code'] > 0) {
                return $this->error($temp['msg']);
            }
            db('factory')->where([
                'id' => $param['id'],
            ])->update([
                'pid' => $param['pid'],
                'level' => $param['level'],
                'type' => $param['type'],
                'name' => $param['name'],
                'update_time' => time(),
            ]);
            return $this->success('保存成功', '');
        }
        $id = $this->request->param('id/d', 0);
        $type_level = $this->request->param('type_level/d', 0);
        $formData = db('factory')->where(['id' => $id])->find();
        $typeMap = ['0' => '自家', '1' => '外发'];
        $this->assign('typeMap', $typeMap);
        $this->factoryServer = new Factory();
        list(, $list_tree) = $this->factoryServer->getAllTree([$formData['pid']]);
        $this->assign('menu_factory', $list_tree);
        $this->assign('formData', $formData);
        $this->assign('type_level', $type_level);
        return $this->fetch('form');
    }

    /**
     * 删除整棵树--标识删除
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/24
     */
    public function del()
    {
        $id = $this->request->param('id/d');
        //1,计算出所有子工厂的id集
        $this->factoryServer->temp = [];
        $ids_array = $this->factoryServer->getChildTree($id);
        $this->factoryServer->temp[] = $id;
        //10,最后修改表的status=0 --不能直接删除--因为与订单关联太深。
        db('factory')->where([
            ['id', 'in', $this->factoryServer->temp],
        ])->update([
            'status' => 0,
        ]);
        return $this->success('删除成功', '');
    }

    private function get_type($param)
    {
        if ($param['pid'] == 0) {
            return intval($param['type']);
        }
        $info = db('factory')->where(['id' => $param['pid']])->find();
        return $info['type'];
    }

    public function index_one()
    {
        if ($this->request->isAjax()) {
            $where = $data = [];
            $whereRaw = '1=1';
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $keyword = $this->request->param('keyword/s');
            $pids = trim($this->request->param('pids/s', ''));
            $where[] = ['level', '=', 1];
            if ($pids != '') {
                $whereRaw .= " and pid in ($pids) OR id in ($pids)";
            } else {
                $where[] = ['pid', '=', 0];
            }
            $where[] = ['status', 'eq', 1];
            if ($keyword) {
                $where[] = ['name', 'like', "%{$keyword}%"];
            }
            $data['data'] = db('factory')->where($where)->whereRaw($whereRaw)->page($page)->limit($limit)->order('order desc, id desc')->select();
            $data['data'] = $this->_dealwith_index($data['data']);
            $data['count'] = db('factory')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        return $this->fetch();
    }

    public function index_two()
    {
        if ($this->request->isAjax()) {
            $where = $data = [];
            $whereRaw = '1=1';
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $keyword = $this->request->param('keyword/s');
            $pids = trim($this->request->param('pids/s', ''));
            $where[] = ['level', '=', 2];
            if ($pids != '') {
                $whereRaw .= " and pid in ($pids) OR id in ($pids)";
            } else {
//                $where[] = ['pid', '=', 0];
            }
            $where[] = ['status', 'eq', 1];
            if ($keyword) {
                $where[] = ['name', 'like', "%{$keyword}%"];
            }
            $data['data'] = db('factory')->where($where)->whereRaw($whereRaw)->page($page)->limit($limit)->order('order desc, id desc')->select();
            $data['data'] = $this->_dealwith_index($data['data']);
            $data['count'] = db('factory')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        return $this->fetch();
    }

    public function index_three()
    {
        if ($this->request->isAjax()) {
            $where = $data = [];
            $whereRaw = '1=1';
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $keyword = $this->request->param('keyword/s');
            $pids = trim($this->request->param('pids/s', ''));
            $where[] = ['level', '=', 3];
            if ($pids != '') {
                $whereRaw .= " and pid in ($pids) OR id in ($pids)";
            } else {
//                $where[] = ['pid', '=', 0];
            }
            $where[] = ['status', 'eq', 1];
            if ($keyword) {
                $where[] = ['name', 'like', "%{$keyword}%"];
            }
            $data['data'] = db('factory')->where($where)->whereRaw($whereRaw)->page($page)->limit($limit)->order('order desc, id desc')->select();
            $data['data'] = $this->_dealwith_index($data['data']);
            $data['count'] = db('factory')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        return $this->fetch();
    }
}